
var Moment = require("../../../utils/moment.js");

var DATE_YEAR = new Date().getFullYear();

var DATE_MONTH = new Date().getMonth() + 1;

var DATE_DAY = new Date().getDate();

Page({

  data: {

    year: '',

    month: '',

    day: '',

    days: {},

    systemInfo: {},

    weekStr: ['日', '一', '二', '三', '四', '五', '六'],

    checkDate: [],

    checkLastDate:'',

    flag_j:0,

    name:'',

    data_arr : [],

    resTimeId:""

  },

  onLoad: function (options) {

    var _this = this;
    var od = options.data_arr;
    
    var od_arr = JSON.parse(od);//od.split(",");
    console.log(od);
    _this.setData({
      name:options.name,
      data_arr: od_arr
    })
    

    let now = new Date();

    let year = now.getFullYear();

    let month = now.getMonth() + 1;

    // 页面初始化 options为页面跳转所带来的参数

    this.createDateListData();

    this.setData({

      year: year,

      month: month

    })

    wx.getSystemInfo({

      success: function (res) {

        _this.setData({

          systemInfo: res,

        });

      }

    })

  },

  onReady: function () {

    // 页面渲染完成

  },

  onShow: function () {



  },



  /**创建日历数据 */

  createDateListData: function (setYear, setMonth) {

    //全部时间的月份都是按0~11基准，显示月份才+1

    let dateArr = []; //需要遍历的日历数组数据

    let arrLen = 0; //dateArr的数组长度

    let now = setYear ? new Date(setYear, setMonth) : new Date();

    let year = setYear || now.getFullYear();

    let nextYear = 0;

    let month = setMonth || now.getMonth();

    //没有+1方便后面计算当月总天数

    let nextMonth = (month + 1) > 11 ? 1 : (month + 1);

    console.log("当前选中月nextMonth：" + nextMonth);

    //目标月1号对应的星期

    let startWeek = new Date(year + '/' + (month + 1) + '/' + '01'); ///=this.getWeek(year, nextMonth, 1); // 
    console.log("时间startWeek:" + startWeek);
    startWeek = startWeek.getDay();
    console.log("目标月1号对应的星期startWeek:" + startWeek);

    //获取目标月有多少天

    let dayNums = this.getTotalDayByMonth(year, nextMonth); //new Date(year, nextMonth, 0).getDate();         

    console.log("获取目标月有多少天dayNums:" + dayNums);

    let obj = {};

    let num = 0;

    if (month + 1 > 11) {

      nextYear = year + 1;

      dayNums = new Date(nextYear, nextMonth, 0).getDate();

    }
    
      for (var j = -startWeek + 1; j <= dayNums; j++) {

        var tempWeek = -1;

        if (j > 0) {

          tempWeek = this.getWeek(year, nextMonth, j);

          console.log(year + "年" + month + "月" + j + "日" + "星期" + tempWeek);

        }

        
        // if ((j < DATE_DAY && year == DATE_YEAR && nextMonth == DATE_MONTH) || 
        //     (year == DATE_YEAR && nextMonth < DATE_MONTH)|| year < DATE_YEAR){
        //   //当天之前的日期不可用
        //   clazz = 'unavailable ' + clazz;
        // }else{
        //   clazz = '' + clazz
        // }
        for (var k = 0; k < this.data.data_arr.length; k++) {
          var clazz = '';

          if (tempWeek == 0 || tempWeek == 6) {
            clazz = 'week'
          }
          var d_arr = this.data.data_arr[k].time.split("-");
          var d_y = d_arr[0];
          var d_m = d_arr[1];
          var d_d = d_arr[2];
          if (d_m.substr(0, 1) == 0) {
            d_m = d_m.substr(1, 1)
          }
          d_m = parseInt(d_m);
          d_m = d_m > 11 ? 1 : d_m;
          if (d_d.substr(0, 1) == 0) {
            d_d = d_d.substr(1, 1)
          }
          if (!(d_y == year.toString() && d_m == nextMonth && d_d == j.toString())) {
            if (k == this.data.data_arr.length-1){
              clazz = 'unavailable ' + clazz;
              /**如果当前日期已经选中，则变色 */
              var date = year + "-" + nextMonth + "-" + j;
              var index = this.checkItemExist(this.data.checkDate, date);
              if (index != -1) {
                clazz = clazz + ' active';
              }

              dateArr.push({

                day: j,

                class: clazz,

                amount: '￥108'

              })
              break;
            }
          } else {
            clazz = '' + clazz;
            /**如果当前日期已经选中，则变色 */
            var date = year + "-" + nextMonth + "-" + j;
            var index = this.checkItemExist(this.data.checkDate, date);
            if (index != -1) {
              clazz = clazz + ' active';
            }

            dateArr.push({

              day: j,

              class: clazz,

              amount: '￥108'

            })
            break;
          }

        }
          
          
      
    }

    this.setData({

      days: dateArr

    })

  },

  /**

   * 上个月

   */

  lastMonthEvent: function () {

    //全部时间的月份都是按0~11基准，显示月份才+1

    let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;

    let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;

    this.setData({

      year: year,

      month: (month + 1)

    })

    this.createDateListData(year, month);
    
    this.setData({
      flag_j:0
    })

  },

  /**

   * 下个月

   */

  nextMonthEvent: function () {

    //全部时间的月份都是按0~11基准，显示月份才+1

    let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;

    let month = this.data.month > 11 ? 0 : this.data.month;

    this.setData({

      year: year,

      month: (month + 1)

    })

    this.createDateListData(year, month);
    
    this.setData({
      flag_j: 0
    })
    
  },

  /*

   * 获取月的总天数

   */

  getTotalDayByMonth: function (year, month) {

    month = parseInt(month, 10);

    var d = new Date(year, month, 0);

    return d.getDate();

  },

  /*

   * 获取月的第一天是星期几

   */

  getWeek: function (year, month, day) {

    var d = new Date(year, month - 1, day);

    return d.getDay();

  },

  /**

   * 点击日期事件

   */

  onPressDateEvent: function (e) {

    var {

      year,

      month,

      day,

      amount

    } = e.currentTarget.dataset;

    console.log("当前点击的日期：" + year + "-" + month + "-" + day);

    //当前选择的日期为同一个月并小于今天，或者点击了空白处（即day<0），不执行

    // if ((day < DATE_DAY && month == DATE_MONTH) || day <= 0 || month < DATE_MONTH || year < DATE_YEAR)

    //   return;
    for (var i = 0; i < this.data.data_arr.length; i++){
      var d_arr = this.data.data_arr[i].time.split("-");
      var d_y = d_arr[0];
      var d_m = d_arr[1];
      var d_d = d_arr[2];
      if (d_m.substr(0, 1) == 0) {
        d_m = d_m.substr(1, 1)
      }
      // d_m = parseInt(d_m);
      // d_m = d_m > 11 ? 1 : d_m;
      if (d_d.substr(0, 1) == 0) {
        d_d = d_d.substr(1, 1)
      }
      if (!(day == d_d && month == d_m && year == d_y)) {
        if (i == this.data.data_arr.length - 1) {
          return;
        }
      } else {
        var _this = this;
        this.setData({
          resTimeId: _this.data.data_arr[i].id
        })
        this.renderPressStyle(year, month, day, amount);
        break;
      }
    }
    
  },

  renderPressStyle: function (year, month, day, amount) {

    var days = this.data.days;

    //渲染点击样式

    for (var j = 0; j < days.length; j++) {

      var tempDay = days[j].day;

      if (tempDay == day) {

        var date = year + "-" + month + "-" + day;

        var obj = {

          day: date,

          amount: amount

        };

        var checkDateJson = this.data.checkDate;

        var index = this.checkItemExist(checkDateJson, date);

        if (index == -1) {
          // if(this.data.checkDate.length == 0){
          //   checkDateJson.push(obj);
          //   days[j].class = days[j].class + ' active';
          // }else{
          //   for (var ii = 0; ii < this.data.checkDate.length; ii++) {
          //     if (ii == this.data.checkDate.length - 1) {
          //       var c_str = this.data.checkDate[ii].day

          //       var index = c_str.lastIndexOf("-");
          //       c_str = c_str.substring(index + 1, c_str.length);

                  //  if (j == parseInt(c_str)){
                  //    checkDateJson.push(obj);
                  //    days[j].class = days[j].class + ' active';
                  //  }
          //       checkDateJson.push(obj);

          //       days[c_str].class = days[c_str].class + ' active';
          //     }
          //   }
          // }
          days[this.data.flag_j].class = days[this.data.flag_j].class.replace('active', ' ');

          checkDateJson.push(obj);

          days[j].class = days[j].class + ' active';

          this.setData({
            flag_j:j
          });

        } else {
          

              checkDateJson.splice(index, 1);

              days[j].class = days[j].class.replace('active', ' ');
          


        }

        this.setData({

          checkDate: checkDateJson,
          checkLastDate:checkDateJson[checkDateJson.length-1].day

        })

        console.log(JSON.stringify(this.data.checkDate));

        break;

      }

    }

    this.setData({

      days: days

    });



  },

  /**检查数组中是否存在该元素 */

  checkItemExist: function (arr, value) {

    for (var i = 0; i < arr.length; i++) {

      if (value === arr[i].day) {

        return i;

      }

    }

    return -1; 

  },

  goto_arili:function(){
    var that = this;
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; 
    prevPage.setData({ 
      checkLastDate: that.data.checkLastDate,
      resTimeId: that.data.resTimeId
    })
    wx.navigateBack({
      delta: 1
    })
  }

})
